<?php

namespace app\index\controller;

use app\model\Store;
use app\model\StoreImage;
use app\model\Composition;
use app\model\CompositionGoods;

class CompositionController extends Base
{
	public function list()
	{
		$keyword = input('post.keyword', '', 'serach_in');
		$where['weid'] = weid();
		$query = Composition::where($where)->with(['goods']);
		if (!empty($keyword)) {
			$query->where('title', 'like', '%' . $keyword . '%');
		}
		$data = $query
			->order('id desc')
			->select()
			->toArray();
		foreach ($data as &$vo) {
			$vo['created_time'] = time_format($vo['created_time']);
			$vo['updated_time'] = time_format($vo['updated_time']);

			$goods = CompositionGoods::setGoodslist($vo['goods']); 
			usort($goods, function($a, $b) {
				return $b['is_main'] <=> $a['is_main']; // 使用太空船操作符
			});
			unset($vo['goods']);
			$vo['goods'] = $goods;
		}
		return $this->json(['data' => $data]);
	}

	public function detail($id)
	{
		$data = Store::find($id);

		if (!empty($data)) {
			$data = $data->toArray();
		}

		$data['store_banner'] = StoreImage::where(['sid' => $id, 'ptype' => 'banner'])
			->field('image')
			->order('sort asc')
			->select()
			->toArray();

		$data['content_img'] = StoreImage::where(['sid' => $id, 'ptype' => 'content'])
			->field('image')
			->order('sort asc')
			->select()
			->toArray();

		$data['create_time'] = time_ymd($data['create_time']);

		$data['address'] =  $data['region_name'] . $data['address'];

		return $this->json(['data' => $data]);
	}
}
